<template>
  <div class="login">
    <div class="title">Security管理系统</div>
    <el-tabs type="border-card" class="demo-tabs" :stretch="true" @tab-click="handleClick" v-model="editableTabsValue">
      <el-tab-pane label="登录">
        <el-form
            ref="ruleFormRef1"
            :model="ruleForm1"
            status-icon
            :rules="rules1"
            class="demo-ruleForm"
            :label-position="labelPosition"
        >
          <el-form-item prop="username">
            <el-input v-model="ruleForm1.username" placeholder="账户" clearable>
              <template #prefix>
                <svg-icon icon="user"></svg-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="password">
            <el-input v-model="ruleForm1.password" type="password" autocomplete="off" maxlength="15" minlength="6"
                      placeholder="密码" clearable>
              <template #prefix>
                <svg-icon icon="password"></svg-icon>
              </template>
            </el-input>
          </el-form-item>
          <el-checkbox style="margin:0px 0px 10px 0px;" v-model="ruleForm1.rememberMe">记住密码</el-checkbox>
          <el-form-item>
            <el-button class="login-btn" type="primary" @click="submitForm(ruleFormRef1)">登录</el-button>
          </el-form-item>
          <el-form-item>
            <el-button class="reset-btn" @click="resetForm(ruleFormRef1)">清空</el-button>
          </el-form-item>
        </el-form>

      </el-tab-pane>
<!--      <el-tab-pane label="注册">-->
<!--        <el-form-->
<!--            ref="ruleFormRef2"-->
<!--            :model="ruleForm2"-->
<!--            status-icon-->
<!--            :rules="rules2"-->
<!--            class="demo-ruleForm"-->
<!--            :label-position="labelPosition">-->
<!--          <el-form-item prop="username">-->
<!--            <el-input v-model="ruleForm2.username" placeholder="账户" clearable>-->
<!--              <template #prefix>-->
<!--                <svg-icon icon="user"></svg-icon>-->
<!--              </template>-->
<!--            </el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item prop="password">-->
<!--            <el-input v-model="ruleForm2.password" type="password" autocomplete="off" maxlength="15" minlength="6"-->
<!--                      placeholder="密码" clearable>-->
<!--              <template #prefix>-->
<!--                <svg-icon icon="password"></svg-icon>-->
<!--              </template>-->
<!--            </el-input>-->
<!--          </el-form-item>-->
<!--          <el-form-item prop="checkPass">-->
<!--            <el-input-->
<!--                v-model="ruleForm2.checkPass"-->
<!--                type="password"-->
<!--                autocomplete="off"-->
<!--                maxlength="15"-->
<!--                minlength="6"-->
<!--                placeholder="确认密码" clearable>-->
<!--              <template #prefix>-->
<!--                <svg-icon icon="password"></svg-icon>-->
<!--              </template>-->
<!--            </el-input>-->
<!--          </el-form-item>-->

<!--        </el-form>-->
<!--        <el-form-item>-->
<!--          <el-button class="login-btn" type="primary" @click="registerForm(ruleFormRef2)">注册</el-button>-->
<!--        </el-form-item>-->
<!--        <el-form-item>-->
<!--          <el-button class="reset-btn" @click="resetForm(ruleFormRef2)">清空</el-button>-->
<!--        </el-form-item>-->
<!--      </el-tab-pane>-->
    </el-tabs>
  </div>
</template>

<script lang="ts" setup>
import Cookies from "js-cookie"
import {decrypt, encrypt} from '@/utils/jsencrypt'
import {reactive, ref, onMounted} from "vue";
import {ElMessage, FormInstance, TabsPaneContext} from "element-plus";
import {checkEmail, validatePass} from "@/utils/validate";
import {doLogin, doRegister} from "@/api/login";
import router from "@/router";
import store from "@/store";


const labelPosition = ref('right')
const MenuData = reactive([{txt: "登录", current: true, type: 'login'}, {
  txt: "注册",
  current: false,
  type: 'register'
},])
const ruleFormRef1 = ref<FormInstance>()
const ruleFormRef2 = ref<FormInstance>()
const editableTabsValue = ref('0')

const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === '') {
    callback(new Error('重复密码不能为空'))
  } else if (value !== ruleForm2.password) {
    callback(new Error("两次密码必须相同"));
  } else {
    callback()
  }
}

const ruleForm1 = reactive({
  username: '',
  password: '',
  rememberMe: false
})
const ruleForm2 = reactive({
  username: '',
  password: '',
  checkPass: '',
})

const rules1 = reactive({
  username: [{validator: checkEmail, trigger: 'blur'}],
  password: [{validator: validatePass, trigger: 'blur'}],
  checkPass: [{validator: validatePass2, trigger: 'blur'}],
})
const rules2 = reactive({
  username: [{validator: checkEmail, trigger: 'blur'}],
  password: [{validator: validatePass, trigger: 'blur'}],
  checkPass: [{validator: validatePass2, trigger: 'blur'}],
})

const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async (valid:any) => {
    if (valid) {
      if (ruleForm1.rememberMe) {
        Cookies.set("username", ruleForm1.username, {expires: 30})
        Cookies.set("password", encrypt(ruleForm1.password), {expires: 30})
        Cookies.set("rememberMe", ruleForm1.rememberMe + '', {expires: 30})
      } else {
        Cookies.remove("username")
        Cookies.remove("password")
        Cookies.remove("rememberMe")
      }
      let params = {
        username: ruleForm1.username,
        password: ruleForm1.password
      }
      const res: any = await doLogin(params)
      const {data, code, msg} = res.data
      console.log(code, data)
      if (code == 200) {
        const {token,menuList,currentUser} = data
        store.commit('SET_MENU_LIST', menuList);
        store.commit('SET_USER_INFO',currentUser);
        store.commit('SET_TOKEN', token);
        ElMessage.success("登录成功!")
        router.replace({path:'/'})
      } else {
        ElMessage.error(msg)
      }
    } else {
      console.log('error submit!')
      return false
    }

  })
}

// const registerForm = (formEl: FormInstance | undefined) => {
//   console.log(formEl)
//   if (!formEl) return
//   formEl.validate((valid) => {
//     if (valid) {
//       let data = {
//         name:ruleForm2.username,
//         pwd:useMd5(ruleForm2.password)
//       }
//       doRegister(data).then((res:any)=>{
//         console.log(res)
//         if (Object.keys(res.data).length!=null){
//           ElMessage({
//             message:'注册成功!',
//             type:'success'
//           })
//           editableTabsValue.value="0";
//         }else {
//           ElMessage({
//             message:'注册失败!',
//             type:'warning'
//           })
//         }
//       }).catch(error=>{
//         console.log(error)
//       })
//       console.log('submit!')
//     } else {
//       console.log('error submit!')
//       return false
//     }
//   })
// }
const handleClick = (tab: TabsPaneContext, event: Event) => {
  console.log(JSON.stringify(tab))
  console.log(JSON.stringify(event))
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const getCookie = () => {
  const username = Cookies.get("username");
  const password = Cookies.get("password");
  const rememberMe = Cookies.get("rememberMe");

  ruleForm1.username = username === undefined ?'' : username,
  ruleForm1.password = password === undefined ?'' : decrypt(password)+'',
  ruleForm1.rememberMe = rememberMe === undefined ? false : Boolean(rememberMe)

}

onMounted(() => {
  getCookie();

})

</script>

<style lang="scss" scoped>
.login {
  width: 100%;
  height: 100%;
  position: absolute;
  background-size: cover;
  background: url("@/assets/images/login-background.jpg") no-repeat center 0;

  .title {
    font-size: 40px;
    margin-top: 10%;
    text-align: center;
    color: deepskyblue;
    font-weight: bold;
  }

  .demo-tabs {
    width: 20%;
    margin: 20px auto;
    background-color: #fff;
  }

  .login-btn {
    margin-left: 0px;
    width: 100%;
  }

  .reset-btn {
    margin-left: 0px;
    width: 100%;
  }
}

</style>